package com.hunk.core.auth.service.impl;

import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hunk.core.auth.dto.RoleDTO;
import com.hunk.core.auth.entity.Role;
import com.hunk.core.auth.repository.RoleRepository;
import com.hunk.core.auth.service.RoleService;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageRequest;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageResponse;
import com.hunk.utils.exception.CustomizeException;

/**
 * Description :<br>
 * 
 * @author HunkDeng
 * @since 2013-4-30
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
    private RoleRepository roleRepository;//注入RoleRepository

    @Override
    @Transactional
    public Role save(Role role) {    	
        return roleRepository.save(role);
    }

    @Override
    @Transactional(readOnly=true)
    public Role findById(String id) {
        return roleRepository.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(String id) {
        roleRepository.delete(id);
    }

	@Override
	@Transactional(rollbackFor = NotFoundException.class)
	public void delete(Role role) throws NotFoundException {
    	if (roleRepository.findOne(role.getId()) == null) {
    		logger.warn("No Role found with id : {" + role.getId() + "}");
    		throw new NotFoundException("No Role found with id : {" + role.getId() + "}");
    	}
		roleRepository.delete(role);
	}

	@Override
	@Transactional(readOnly=true)
	public JpaPageResponse<Role> findPageByParams(
			JpaPageRequest<Role> pageRequest) {
		return new JpaPageResponse<Role>(roleRepository.findAll(
				pageRequest.setSort(RoleRepository.defaultSort).getPageRequest()
				));
	}

	@Override
	public Set<RoleDTO> findAllAsTree() {
		Set<RoleDTO> roles = new LinkedHashSet<RoleDTO>();
		for (Role role : roleRepository.findAll(RoleRepository.defaultSort)) {
			RoleDTO roleDto = new RoleDTO(role);
			roles.add(roleDto);
		}
		return roles;
	}
}
